package com.techysky.shiro;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.techysky.entity.Permission;
import com.techysky.entity.Role;
import com.techysky.entity.User;
import com.techysky.repository.PermissionRepository;
import com.techysky.repository.RoleRepository;
import com.techysky.repository.UserRepository;

public class UserRealm extends AuthorizingRealm {

	// 获取授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		String RoleId = ShiroUtils.getRoleId();
		RoleRepository roleRepository = ApplicationContextRegister.getBean(RoleRepository.class);
		PermissionRepository permissionRepository = ApplicationContextRegister.getBean(PermissionRepository.class);
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Set<String> permsSet = new HashSet<>();
		Role role = roleRepository.findOne(RoleId);
		if(role!=null){
			// 根据角色查询 权限表
			Permission ps = permissionRepository.findByRoleId(role.getId());
				if (StringUtils.isNotBlank(ps.getPerCode())) {
					permsSet.addAll(Arrays.asList(ps.getPerCode().trim().split(",")));
				}
			info.addStringPermissions(permsSet);
		}
		System.out.println("权限验证成功");
		return info;
	}

	// 认证.登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = (String) token.getPrincipal();
		String userPassword ="";
		if(token.getCredentials()!=null){
		  userPassword = new String((char[]) token.getCredentials());
		}
		UserRepository userRepository = ApplicationContextRegister.getBean(UserRepository.class);
		User user = userRepository.findByUserNameAndUserPassword(userName, userPassword);
		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		// 密码错误
		if (!userPassword.equals(user.getUserPassword())) {
			throw new IncorrectCredentialsException("账号或密码不正确");
		}
		
		SecurityUtils.getSubject().getSession().setAttribute("user", user);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, userPassword, getName());
		return info;
	}

}
